package highscore;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;

import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;

public class Highscore {
	public Highscore() {
		try {
			rs = RecordStore.openRecordStore("score", true);
			
			rsID = 0;
		} catch (RecordStoreException e) {
			e.printStackTrace();
		}
	}
	public void WriteNewHighscore(int points) {
		ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
		DataOutputStream dataOutStream = new DataOutputStream(byteOutStream);
		try {
			dataOutStream.writeInt(points);

			byte[] outByte = byteOutStream.toByteArray();
			rsID = rs.addRecord(outByte, 0, outByte.length);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public int ReadHighscore() {
		RecordEnumeration re = null;
		int score = 0;
		try {
			re = rs.enumerateRecords(null, null, true);
			while(re.hasNextElement()) {
				int id = re.nextRecordId();
			
				if (id == rsID) {
					ByteArrayInputStream bais = new ByteArrayInputStream(rs.getRecord(id));
					DataInputStream dis = new DataInputStream(bais);
					score = dis.readInt();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return score;
	}
	
	public boolean IsNewHighscore(int points) {
		int p = ReadHighscore();
		if (points > p)
			return true;
		return false;
	}
	
	private int rsID;
	private RecordStore rs;
}
